package com.dandan.testcollection.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.Paint;
import android.graphics.Path;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ListView;

import com.dandan.testcollection.CalcUtil;
import com.dandan.testcollection.bean.KLineBean;
import com.dandan.testcollection.bean.Point;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Dandan on 2018/6/13.
 */

/**
 *  根据金色财经所给的接口画出其简易折线图
 */
public class KLine extends View {
    private KLineBean kLineBean;
    private boolean isCache = false;
    private int paintColor = 0xff1ea89c;
    private Paint paint;
    private Double priceHigh = 0d;
    private Double priceLow = 999999999d;
    private boolean showLeftNumber = true;
    private double offY;
    private double offX;
    private boolean showTopPoint = true;
    private List<Point> points = new ArrayList<>();
    private Paint backgroundLinePaint;
    private boolean control = true;
    private Paint linePaint;
    private float lineHeight;
    private int leftTime;
    private int index = -1;
    private Paint xLinePaint;
    private Path path;
    private float x;
    private float y;
    private float x1;
    private float y1;
    private Paint.FontMetrics metrics;
    private double singleHeight;
    private OnCurrentPriceListener onCurrentPriceListener;
    private int currentIndex = -1;


    public KLine(Context context) {
        this(context, null);
    }

    public KLine(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public KLine(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }


    @Override
    protected void onDraw(Canvas canvas) {
        if (kLineBean == null) {
            return;
        }
        if (!isCache)
            initPaint();

        lineHeight = getHeight() /10.0f * 9.0f;
        points.clear();
        leftTime = 1;
        //预计5个点  单一价格
        offY = CalcUtil.div(priceHigh - priceLow, 5d, 2);
        singleHeight = CalcUtil.div(lineHeight, 6d, 2);
        //此地的22是因为显示24个小时 .只有23个数. 头尾再-1
        //不-1是因为右面想留出1份的空位
        offX = CalcUtil.div(getWidth(), kLineBean.getPrices().size() + leftTime, 0);
        /**
         * 左面预留份数
         */

        if (showLeftNumber) {
            leftTime = 3;
            //把屏幕宽度分成27份 . 左面文字占4份  右面空位占1 (如果需要)
            offX = CalcUtil.div(getWidth(), kLineBean.getPrices().size() + leftTime, 0);
            //显示左面的价格条
            for (int i = 0; i <= 5; i++) {
                canvas.drawText(CalcUtil.add(priceLow, CalcUtil.mul(offY, i)) + "", 10, (float) CalcUtil.sub(lineHeight, CalcUtil.mul(i , singleHeight)), paint);
            }
        }
        for (int i = 0; i < kLineBean.getPrices().size(); i++) {
            double 当前价格减最低价 = kLineBean.getPrices().get(i) - priceLow;
            double 高低差 = priceHigh - priceLow;
            double 屏幕每份高度乘5_实际图标高度 = CalcUtil.mul(singleHeight, 5);
            double 高度比例 = CalcUtil.div(当前价格减最低价, 高低差, 2);
            double 最终Y = CalcUtil.mul(高度比例, 屏幕每份高度乘5_实际图标高度);
            最终Y = lineHeight  - 最终Y;
            points.add(new Point(
                    CalcUtil.mul(offX, (leftTime + i)),
                    最终Y
                    )
            );
            if(showTopPoint)
                canvas.drawCircle((float) points.get(i).getX(), (float) points.get(i).getY(), 10, paint);
        }
        path = new Path();
        path.moveTo((float) points.get(0).getX(), (float) points.get(0).getY());
        //画线
        canvas.drawLine((float) points.get(0).getX(), (float) 0,(float) points.get(0).getX(),lineHeight ,backgroundLinePaint);
        //写字
        Paint.FontMetrics metrics1 =backgroundLinePaint.getFontMetrics();
        String text0 = kLineBean.getDatetimes().get(0).substring(11,16);
        canvas.drawText(text0,(float) points.get(0).getX()-backgroundLinePaint.measureText(text0)/2,getHeight() - (metrics1.descent+Math.abs(metrics1.ascent))/2 ,backgroundLinePaint);

        for(int i  = 1 ; i < points.size() ; i++)
        {
            x = (float) ((float) points.get(i-1).getX() + offX/2.0);
            x1 = x;
            y =  (float) points.get(i-1).getY();
            y1 =  (float) points.get(i).getY();

            path.cubicTo(x, y, x1, y1,(float) points.get(i).getX(), (float) points.get(i).getY());
            if(i%4==0) {
                canvas.drawLine((float) points.get(i).getX(), (float) 0, (float) points.get(i).getX(), lineHeight, backgroundLinePaint);
                metrics = backgroundLinePaint.getFontMetrics();
                float textY = getHeight() - (metrics.descent+Math.abs(metrics.ascent))/2 ;
                float textX = (float) points.get(i).getX()-backgroundLinePaint.measureText( kLineBean.getDatetimes().get(i).substring(11,16))/2;
                canvas.drawText( kLineBean.getDatetimes().get(i).substring(11,16),textX,textY,backgroundLinePaint);
            }
            //证明正在触控
            if(index != -1)
            {
                Path hoLine = new Path();
                Path veLine = new Path();
                hoLine.moveTo((float) points.get(0).getX(),(float) points.get(index).getY());
                hoLine.lineTo((float) points.get(points.size()-1).getX(),(float) points.get(index).getY());
                veLine.moveTo((float) points.get(index).getX(),0);
                veLine.lineTo((float) points.get(index).getX(),lineHeight);
                canvas.drawPath(hoLine,xLinePaint);
                canvas.drawPath(veLine,xLinePaint);
                canvas.drawCircle((float) points.get(index).getX(),(float) points.get(index).getY(),10f,xLinePaint);
                if(onCurrentPriceListener != null)
                {
                    onCurrentPriceListener.onCurrentPrice(kLineBean.getDatetimes().get(index),kLineBean.getPrices().get(index));
                }
            }

        }
        canvas.drawPath(path,linePaint);


        super.onDraw(canvas);
    }

    private void initPaint() {
        isCache = true;
        paint = new Paint();
        paint.setAntiAlias(true);
        paint.setStrokeWidth(5);
        paint.setStyle(Paint.Style.FILL);
        paint.setTextSize(32);
        paint.setColor(paintColor);

        linePaint = new Paint();
        linePaint.setAntiAlias(true);
        linePaint.setStrokeWidth(3);
        linePaint.setStrokeCap(Paint.Cap.ROUND);
        linePaint.setStyle(Paint.Style.STROKE);
        linePaint.setColor(Color.parseColor("#ff0000"));
        linePaint.setStrokeMiter(2f);

        backgroundLinePaint = new Paint();
        backgroundLinePaint.setAntiAlias(true);
        backgroundLinePaint.setStyle(Paint.Style.STROKE);
        backgroundLinePaint.setTextSize(32);
        backgroundLinePaint.setColor(Color.parseColor("#999999"));

        //虚线笔
        xLinePaint = new Paint();
        xLinePaint.setStyle(Paint.Style.STROKE);
        xLinePaint.setAntiAlias(true);
        xLinePaint.setStrokeWidth(2);
        xLinePaint.setColor(Color.parseColor("#4d7aad"));
        xLinePaint.setPathEffect(new DashPathEffect(new float[]{20f,10f}, 0));
    }

    public KLine setData(@NonNull KLineBean kLineBean) {
        this.kLineBean = kLineBean;
        for (int i = 0; i < kLineBean.getPrices().size(); i++) {
            if (kLineBean.getPrices().get(i) > priceHigh) {
                priceHigh = kLineBean.getPrices().get(i);
            }
            if (kLineBean.getPrices().get(i) < priceLow) {
                priceLow = kLineBean.getPrices().get(i);
            }
        }
        invalidate();
        return this;
    }

    public KLine setColor(int paintColor) {
        this.paintColor = paintColor;
        initPaint();
        invalidate();
        return this;
    }


    public KLine setShowLeftNumber(boolean showLeftNumber) {
        this.showLeftNumber = showLeftNumber;
        invalidate();
        return this;
    }

    public KLine setShowTopPoint(boolean showTopPoint) {
        this.showTopPoint = showTopPoint;
        invalidate();
        return this;
    }

    public KLine setOnCurrentPriceListener(OnCurrentPriceListener onCurrentPriceListener) {
        this.onCurrentPriceListener = onCurrentPriceListener;
        invalidate();
        return this;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        float ex = 0f;
        switch (event.getAction())
        {
            case MotionEvent.ACTION_DOWN:
                ex = event.getX();
                currentIndex = (int) CalcUtil.sub((int)CalcUtil.div(ex,offX,2),leftTime);
                if(currentIndex != index) {
                    index = currentIndex;
                    invalidate();
                }
                break;
            case MotionEvent.ACTION_MOVE:
                ex = event.getX();
                currentIndex = (int) CalcUtil.sub((int)CalcUtil.div(ex,offX,2),leftTime);
                if(currentIndex != index) {
                    index = currentIndex;
                    invalidate();
                }
                break;
            case MotionEvent.ACTION_UP:
                index = -1;
                currentIndex = -1;
                invalidate();
                break;
        }
        return true;
    }

    public interface OnCurrentPriceListener{
        void onCurrentPrice(String time, Double price);
    }
}
